<?php

    require '/var/www/pdd/wxpay11/lib/WxPay.Api.php';
    ini_set('date.timezone','Asia/Shanghai');
//    include './wxpay11/lib/WxPay.Api.php';
    $wxpay = new WxPayApi();
    $input = new WxPayOrderQuery();

    $dbms='mysql';     //数据库类型
    $host='127.0.0.1'; //数据库主机名
    $dbName='pdd';     //使用的数据库
    $user='root';      //数据库连接用户名
    $pass='XiaoL511';  //对应的密码
    $dsn="$dbms:host=$host;dbname=$dbName";
    try {
        $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
        $list = $dbh->query('SELECT id,number,time,uid,integral from orders where state = 1');
        foreach ($list as $row) {

            $input->SetOut_trade_no($row['number']);
            $info = $wxpay->orderQuery($input);
            if ($info['return_code'] == 'SUCCESS' && $info['result_code'] == 'SUCCESS' && $info['trade_state'] == 'SUCCESS')
            {
                if ($info['trade_state'] == 'SUCCESS'){
                    $glist = $dbh->query('SELECT b.gid,b.num FROM orders a INNER JOIN o_details b ON a.id = b.oid WHERE a.id = '.$row['id']);
                    foreach ($glist as $v){
                         $dbh->query('UPDATE goods SET stock = stock+'.$v['num'].' WHERE id ='.$v['gid']);
                         $dbh->query('UPDATE goods SET sold = stock-'.$v['num'].' WHERE id ='.$v['gid']);


                    }
                    $dbh->query('UPDATE orders SET state = 2 WHERE id ='.$row['id']);
                    continue;
                }
                if ($info['trade_state'] == 'USERPAYING')
                    continue;
            }
            if($info['trade_state'] == 'REFUND')
            {
                $dbh->query('UPDATE orders SET state = 4 WHERE id ='.$row['id']);
            }
            if ($info['trade_state'] == 'CLOSED' || $info['trade_state'] == 'NOTPAY'){
                $vip = $dbh->query('SELECT id FROM `vip` WHERE `state` = 1 AND `stop` > '. time() .' AND `uid` ='.$row['uid']);
                $vip = $vip->rowCount();
                    $i = $dbh->query('UPDATE users SET integral = integral + '.$row['integral'] . ' WHERE id ='.$row['uid']);
                if (!$i) continue;
            }
            if (time() > $row['time']+1200) {
                $dbh->query('UPDATE orders SET state = 5 WHERE id ='.$row['id']);
                continue;
            }
            $dbh->query('UPDATE orders SET state = 5 WHERE id ='.$row['id']);
        }
        $dbh = null;
    } catch (PDOException $e) {
        die ("Error!: " . $e->getMessage() . "<br/>");
    }



